import { ResourceFileType, formatEnumForSelect } from '@/views/enum/common';
import { IFormConfig, IFormData, IFormItemConfig, IJlFormInstance } from '@jl/element-plus';
import { ref } from 'vue';
import { getLocalUploadFiles, getResourceCategoryTree } from '@/api/resource';
import { useRequest } from '@jl/common/composable';

export function create() {
  const fileTypeTipsMap = {
    osgb: '请压缩OSGB模型为zip或rar后上传，并设定数据处理',
    shp: '请压缩SHP模型为zip或rar后上传',
    kml: '请直接上传KML模型',
    json: '请直接上传GEOJSON模型',
    '3dtiles': '请压缩3DTILES模型为zip或rar后上传',
    gltf: '请直接上传GLTF/GLB模型',
    'tif-dem': '请直接上传TIF-dem模型,并设定数据处理',
    'tif-dom': '请直接上传TIF-dom模型,并设定数据处理',
    jlg: '请压缩JIL模型为zip或rar后上传',
    terrain: '请压缩TERRAIN模型为zip或rar后上传',
    img: '请直接上传图片',
    'stp-step': '请直接上传STP/STEP模型,请设定数据处理',
    dxf: '直接上传模型,请设定数据处理',
    obj: '请压缩模型为zip或rar后上传,并设定数据处理',
    fbx: '请直接上传FBX模型,请设定数据处理',
    dgn: '请直接上传DGN模型,请设定数据处理',
    skp: '请直接上传SKP模型,请设定数据处理',
    '3ds': '请直接上传3DS模型,请设定数据处理',
    las: '请直接上传LAS模型',
    '3dxml': '请直接上传3DXML模型,并设定数据处理',
    '3dm': '请直接上传3DM模型,并设定数据处理',
    ifc: '请直接上传IFC模型,并设定数据处理',
    nwd: '请直接上传NWD模型,并设定数据处理',
    rvt: '请直接上传RVT模型,并设定数据处理',
  };
  const ModelPrecisionOptionsArr = ref<{ label: string; value: string | number }[]>([]);
  const formRef = ref<IJlFormInstance>();
  const formConfig: IFormConfig = { gutter: 24, labelWidth: 90 };
  // 分类 tree
  const { run: getResourceCategoryTreeRun, data: getResourceCategoryTreeData } = useRequest<
    any,
    any
  >(getResourceCategoryTree, {});
  const categoryTree = ref<any[]>([]);
  const formData = ref<IFormData>({
    fileResName: '',
    fileType: 'gltf',
    dataType: '',
    resUrl: '',
    filePath: '',
    resCover: '',
    matDesp: '',
    changeType: '',
    fileCategoryId: '',
    ModelPrecision: 0,
    IsDraco: true,
    IsExportComponent: false,
  });
  const changeType = ref<string>('');
  // 是否存在导出数据
  const uploadOptions = ref('1');
  const fileCategoryName = ref('');
  // 大文件上传列表
  const treeData = ref<any[]>([]);
  const { run, data } = useRequest<any, any>(getLocalUploadFiles, {});
  const uploadOptionsChange = async (value: any) => {
    if (value === '2') {
      // 大文件上传列表
      await run();
      const arr = Array.from(data.value);
      treeData.value = recursionGenerateTree('root', arr);
    }
  };

  const formItemConfig = ref<IFormItemConfig>([
    {
      type: 'input',
      key: 'fileResName',
      label: '资源名称',
      span: 24,
      maxLength: '50',
      placeholder: '请输入资源名称',
      emits: new Set(['change']),
      rules: [
        {
          required: true,
          message: '请输入资源名称',
        },
      ],
    },
    {
      type: 'slot',
      key: 'fileCategoryId',
      slotName: 'slotClassification',
      label: '分类',
      span: 24,
      options: [],
      rules: [
        {
          required: true,
          message: '请输入选择分类',
        },
      ],
    },
    {
      type: 'slot',
      slotName: 'slotFileType',
      key: 'fileType',
      label: '数据格式',
      span: 24,
      placeholder: '请选择',
      emits: new Set(['change']),
      options: formatEnumForSelect(ResourceFileType),
      rules: [
        {
          required: true,
          message: '请选择数据格式',
        },
      ],
    },
    {
      type: 'slot',
      slotName: 'slotResUrl',
      key: 'resUrl',
      label: '资源文件',
      span: 24,
      rules: [{ required: true, message: '请选择资源文件' }],
    },
    {
      type: 'slot',
      slotName: 'slotResCover',
      key: 'resCover',
      label: '资源封面',
      span: 24,
    },
    {
      type: 'textarea',
      maxLength: '200',
      key: 'matDesp',
      label: '资源描述',
      placeholder: '请输入数据资源描述，不超过200个字符',
      span: 24,
    },
  ]);

  const getFormItemByKey = (key: string) => {
    return formItemConfig.value.find((item: any) => {
      return item.key === key;
    });
  };

  watch(
    () => formData.value.fileType,
    () => {
      formItemConfig.value = formItemConfig.value.filter(
        (item: any) =>
          !['dataType', 'accuracy', 'changeType', 'leftPosition', 'rightPosition'].includes(
            item.key
          )
      );

      const dataType = {
        type: 'slot',
        slotName: 'slotDataType',
        key: 'dataType',
        label: '数据处理',
        span: 24,
        placeholder: '请选择',
        emits: new Set(['change']),
        options: [] as any,
        disabled: formItemConfig.value[1].disabled,
        rules: [
          {
            required: true,
            message: '请选择数据处理',
          },
        ],
      };
      const dataProcessingTerm = {
        type: 'slot',
        slotName: 'slotDataProcessing',
        key: 'changeType',
        label: '数据处理',
        span: 24,
        rules: [
          {
            required: true,
            message: '请选择数据处理',
          },
        ],
      };
      const fileType = [
        'stp-step',
        'dxf',
        'obj',
        'fbx',
        'dgn',
        'skp',
        '3ds',
        '3dm',
        '3dxml',
        'ifc',
        'nwd',
        'rvt',
      ];
      if (formData.value.fileType === ResourceFileType.osgb.code) {
        dataType.options = [
          { label: '不处理', value: '1' },
          { label: 'OSGB转换为3dtiles', value: '2' },
        ];
        formItemConfig.value.splice(3, 0, dataType);
      } else if (formData.value.fileType === ResourceFileType['tif-dom'].code) {
        dataType.options = [
          { label: '不处理', value: '1' },
          { label: 'XYZ切图', value: '2' },
          { label: '图层处理', value: '3' },
        ];
        formItemConfig.value.splice(3, 0, dataType);
      } else if (formData.value.fileType === ResourceFileType['tif-dem'].code) {
        dataType.options = [
          { label: '不处理', value: '1' },
          { label: '图层处理', value: '2' },
        ];
        formItemConfig.value.splice(3, 0, dataType);
      } else if (formData.value.fileType === ResourceFileType.img.code) {
        dataType.options = [
          { label: '不处理', value: '1' },
          { label: '坐标设置', value: '2' },
        ];
        formItemConfig.value.splice(3, 0, dataType);
        const leftPosition = {
          type: 'slot',
          slotName: 'slotLeftPosition',
          key: 'leftPosition',
          label: '左上角坐标',
          span: 24,
        };
        const rightPosition = {
          type: 'slot',
          slotName: 'slotRightPosition',
          key: 'rightPosition',
          label: '右上角坐标',
          span: 24,
        };
        formData.value.leftPosition = {
          longitude: '',
          latitude: '',
        };
        formData.value.rightPosition = {
          longitude: '',
          latitude: '',
        };
        formItemConfig.value.splice(3, 0, leftPosition, rightPosition);
      } else if (fileType.includes(formData.value.fileType)) {
        formData.value.changeType = 10;
        formItemConfig.value.splice(3, 0, dataProcessingTerm);
        // 默认 'obj', 'fbx', 'dxf', '3ds'
        const obj = {
          height: 7,
          center: 4,
          low: 0,
        };
        if (['stp-step'].includes(formData.value.fileType)) {
          obj.height = 7;
          obj.center = 6;
        } else {
          obj.height = 15;
          obj.center = 6;
        }
        ModelPrecisionOptionsArr.value = [
          {
            label: '高',
            value: obj.height,
          },
          {
            label: '中',
            value: obj.center,
          },
          {
            label: '低',
            value: obj.low,
          },
        ];
      }
    }
  );

  watch(
    () => formData.value.fileCategoryId,
    (categoryId: string) => {
      // 白模
      const categoryIdArr = [
        'eeaa9f19-5b5d-4882-962f-77fb586f3508',
        '25ac466f-f7c2-4e88-9529-5864f322bb4e',
        '5b46c230-a903-4cce-a8d6-7b57bf23fafe',
      ];
      let optiomns: any = [];
      if (categoryIdArr.includes(categoryId)) {
        if (categoryId === 'eeaa9f19-5b5d-4882-962f-77fb586f3508') {
          optiomns = formatEnumForSelect(ResourceFileType, ['shp', 'kml', 'json', '3dtiles']);
        }
        // 行政边界
        else if (categoryId === '25ac466f-f7c2-4e88-9529-5864f322bb4e') {
          optiomns = formatEnumForSelect(ResourceFileType, ['shp', 'kml', 'json']);
        }
        // 道路
        else if (categoryId === '5b46c230-a903-4cce-a8d6-7b57bf23fafe') {
          optiomns = formatEnumForSelect(ResourceFileType, ['shp', 'kml', 'json']);
        }
      } else {
        optiomns = formatEnumForSelect(ResourceFileType);
      }
      const currentIndex = formItemConfig.value.findIndex((item) => item.key === 'fileType');
      formItemConfig.value[currentIndex].options = optiomns;
    }
  );

  onMounted(async () => {
    // 分类列表获取
    // getCategoryTree();
  });

  const getCategoryTree = async (parentId?: string) => {
    await getResourceCategoryTreeRun();
    const { list } = getResourceCategoryTreeData.value;
    if (formData.value.fileCategoryId !== '') {
      const currentObj = list.find(
        (item: any) => item.categoryId === formData.value.fileCategoryId
      );
      fileCategoryName.value = currentObj.categoryName;
    }
    categoryTree.value = generateCategoryTree(parentId || '-1', list);
    return categoryTree.value;
  };
  const fileCurrentObj: any = computed(() => {
    if (JSON.stringify(data.value) === '{}') return {};
    return data.value.find((item: any) => item.value === formData.value.filePath);
  });

  // 生成本地文件列表
  const recursionGenerateTree = (pid: string, arr: any[]) => {
    const array: any[] = [];
    arr.forEach((item) => {
      if (item.parentId === pid) {
        item.children = recursionGenerateTree(item.value, arr); // 接收子节点
        array.push(item);
      }
    });
    return array;
  };

  const filePathCurrentObj = ref({});
  const filePathChange = (item: any) => {
    filePathCurrentObj.value = item;
    formData.value.resUrl = item.value;
    formData.value.filePath = item.value;
  };

  // 生成分类tree
  const generateCategoryTree = (pid: string, arr: any[]) => {
    const array: any[] = [];
    arr.forEach((item) => {
      if (item.parentId === pid) {
        item.children = generateCategoryTree(item.categoryId, arr); // 接收子节点
        array.push(item);
      }
    });
    return array;
  };

  return {
    formRef,
    formConfig,
    formData,
    changeType,
    formItemConfig,
    treeData,
    fileCurrentObj,
    filePathChange,
    filePathCurrentObj,
    fileCategoryName,
    uploadOptions,
    categoryTree,
    getCategoryTree,
    ModelPrecisionOptionsArr,
    getFormItemByKey,
    uploadOptionsChange,
    fileTypeTipsMap,
  };
}
